/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.seckill.platform.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.StationEnum;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.i18n.I18nMessage;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.seckill.common.model.Seckill;
import com.yami.shop.seckill.common.service.SeckillService;
import com.yami.shop.seckill.common.service.SeckillSkuService;
import com.yami.shop.seckill.platform.dto.SeckillProdDto;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import com.yami.shop.service.ProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * @author LGH
 * @date 2019-08-28 09:36:59
 */
@RestController
@AllArgsConstructor
@RequestMapping("/platform/seckill")
@Api(tags = "平台端秒杀接口")
public class SeckillController {

    private final SeckillService seckillService;

    private final ProductService productService;

    private final ApplicationEventPublisher eventPublisher;

    private final SeckillSkuService seckillSkuService;

    private final OfflineHandleEventService offlineHandleEventService;

    @GetMapping("/page")
    @ApiOperation(value = "分页查找秒杀信息")
    public ServerResponseEntity<IPage<Seckill>> getSeckillPage(PageParam<Seckill> page, Seckill seckill) {
        IPage<Seckill> seckillPage = seckillService.getPlatformSeckillPage(page, seckill);
        return ServerResponseEntity.success(seckillPage);
    }

    @GetMapping("/info/{seckillId}")
    @ApiOperation(value = "通过id查询秒杀信息")
    @ApiImplicitParam(name = "seckillId", value = "秒杀id", required = true, dataType = "Long")
    public ServerResponseEntity<SeckillProdDto> getById(@PathVariable("seckillId") Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        SeckillProdDto dto = new SeckillProdDto();
        dto.setSeckill(seckill);
        dto.setSeckillSkus(seckillSkuService.listSeckillSkuBySeckillId(seckillId));
        Product product = productService.getProductByProdId(seckill.getProdId(), I18nMessage.getDbLang());
        dto.setProd(product);
        return ServerResponseEntity.success(dto);
    }

    @PutMapping("/invalid/{seckillId}")
    @ApiOperation(value = "通过id使秒杀商品失效")
    @ApiImplicitParam(name = "seckillId", value = "秒杀id", required = true, dataType = "Long")
    public ServerResponseEntity<Void> invalidById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        seckillService.invalidById(seckill);
        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{seckillId}")
    @ApiOperation(value = "通过id删除秒杀信息")
    @ApiImplicitParam(name = "seckillId", value = "秒杀id", required = true, dataType = "Long")
    public ServerResponseEntity<Void> removeById(@PathVariable Long seckillId) {
        Seckill seckill = seckillService.getById(seckillId);
        Integer oldStatus = seckill.getStatus();
        if (Objects.equals(StationEnum.NORMAL.getValue(), seckill.getStatus())) {
            // 秒杀活动未关闭，无法删除
            throw new YamiShopBindException("yami.seckill.cannot.delete");
        }
        seckillService.invalidById(seckill);
        seckill.setIsDelete(1);
        seckill.setStatus(oldStatus);
        seckillService.updateById(seckill);
        productService.removeProdCacheByProdId(seckill.getProdId());
        seckillSkuService.removeSeckillSkuCacheBySeckillId(seckill.getSeckillId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEventBySeckillId/{seckillId}")
    @PreAuthorize("@pms.hasPermission('platform:seckill:info')")
    @ApiOperation(value = "通过活动id获取下线信息")
    @ApiImplicitParam(name = "seckillId", value = "秒杀id", required = true, dataType = "Long")
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByDiscountId(@PathVariable("seckillId") Long seckillId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.SECKILL.getValue(), seckillId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:seckill:update')")
    @ApiOperation(value = "下线活动")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Seckill seckill = seckillService.getById(offlineHandleEvent.getHandleId());
        if (seckill == null) {
            // 未找到该秒杀活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        if (Objects.equals(seckill.getIsDelete(),1)) {
            //活动已被删除，请刷新页面重试
            throw new YamiShopBindException("yami.active.is.delete");
        }
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        seckillService.offline(seckill, offlineHandleEvent.getOfflineReason(), sysUserId);
        // 移除缓存
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(seckill.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }

    @PostMapping("/auditSeckill")
    @PreAuthorize("@pms.hasPermission('platform:seckill:update')")
    @ApiOperation(value = "秒杀活动提交审核")
    public ServerResponseEntity<Void> auditSeckill(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        Seckill seckill = seckillService.getById(offlineHandleEventAuditParam.getHandleId());
        if (seckill == null) {
            // 未找到该秒杀活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        seckillService.auditSeckill(offlineHandleEventAuditParam, sysUserId);
        // 移除缓存
        seckillService.removeSeckillCache(seckill.getSeckillId(), seckill.getProdId());
        eventPublisher.publishEvent(new EsProductUpdateEvent(seckill.getProdId(), null, EsOperationType.UPDATE));
        return ServerResponseEntity.success();
    }
}
